/**
 * 系统管理 用户管理
 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/repair/repairList' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="用户状态：">
        <el-select
          size="small"
          style="width: 105px"
          v-model="formInline.status"
          placeholder="请选择"
        >
          <el-option label="全部" value=""></el-option>
          <el-option label="正常" value="0"></el-option>
          <el-option label="已锁定" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-input
          size="small"
          v-model="formInline.userName"
          placeholder="输入用户名"
        ></el-input>
      </el-form-item>
      <el-form-item label="">
        <el-input
          size="small"
          v-model="formInline.phonenumber"
          placeholder="输入手机号"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户类型：">
        <el-select
          size="small"
          style="width: 105px"
          v-model="formInline.userType"
          placeholder="请选择"
        >
          <el-option label="全部" value=""></el-option>
          <el-option label="管理员" value="0"></el-option>
          <el-option label="普通用户" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="search"
          >搜索</el-button
        >
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="handleEdit()"
          >添加</el-button
        >
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table
      size="small"
      :data="userData"
      highlight-current-row
      v-loading="loading"
      border
      element-loading-text="拼命加载中"
      style="width: 100%"
    >

      
      <el-table-column
        align="center"
        sortable
        prop="userName"
        label="用户名"
        width="120"
      >
      </el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="nickName"
        label="姓名"
        width="120"
      >
      </el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="phonenumber"
        label="手机号"
        width="120"
      >
      </el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="sex"
        label="性别"
        min-width="50"
      >
      <template slot-scope="scope">
          <div>{{ scope.row.sex==1?"女":"男" }}</div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="email"
        label="邮件"
        min-width="120"
      >
      </el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="updateTime"
        label="修改时间"
        min-width="120"
      >
        <template slot-scope="scope">
          <div>{{ scope.row.updateTime }}</div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="status"
        label="状态"
        min-width="50"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status == 1 ? fshow : nshow"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="editType(scope.$index, scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <!-- 角色列表 -->
      <el-table-column  
        align="center"
        sortable
        prop="roles"
        label="用户权限"
        width="170">
         <template slot-scope="scope">
          <!-- <div>{{ scope.row.editTime }}</div> -->
           <!-- <span v-for="r in scope.row.roleList">{{r}}</span> -->
             <el-tag style="margin:0 2px;" effect="plain" type="" size="mini"
              v-for="(val,index) in scope.row.roles" :key="index" >{{ val.name }}</el-tag>
           <!-- <el-button v-for="r in scope.row.roleList">{{r}}</el-button> -->
        </template>
       
      </el-table-column>
      <el-table-column label="操作" min-width="300">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="deleteUser(scope.$index, scope.row)"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="success"
            @click="resetpwd(scope.$index, scope.row)"
            >重置密码</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination
      v-bind:child-msg="pageparm"
      @callFather="callFather"
    ></Pagination>
    <!-- 编辑界面 -->
    <el-dialog
      :title="title"
      :visible.sync="editFormVisible"
      width="33%"
      @click="closeDialog('edit')"
    >
      <el-form
        label-width="110px"
        ref="editForm"
        :model="editForm"
        :rules="rules"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input
            size="small"
            v-model="editForm.userName"
            auto-complete="off"
            placeholder="请输入用户名"
            :disabled="isEditOrAdd"
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="nickName">
          <el-input
            size="small"
            v-model="editForm.nickName"
            auto-complete="off"
            placeholder="请输入姓名"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="角色" prop="roleId">
          <el-select
            size="small"
            v-model="editForm.roleId"
            placeholder="请选择"
            class="userRole"
          >
            <el-option label="公司管理员" value="1"></el-option>
            <el-option label="普通用户" value="2"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="角色" prop="roleList">
          <el-checkbox-group v-model="editForm.roleList">
            <el-checkbox-button
              v-for="role in allRoles"
              :label="role.id"
              :key="role.id"
              >{{ role.name }}</el-checkbox-button
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="是否为管理员" prop="userType">
          <el-radio v-model="editForm.userType" label="0">是</el-radio>
          <el-radio v-model="editForm.userType" label="1">否</el-radio>
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input
            size="small"
            v-model="editForm.phonenumber"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮件" prop="email">
          <el-input
            size="small"
            v-model="editForm.email"
            placeholder="请输入邮箱地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio v-model="editForm.sex" label="0">男</el-radio>
          <el-radio v-model="editForm.sex" label="1">女</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog('edit')">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          class="title"
          @click="submitForm('editForm')"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入请求方法
import Pagination from "../../components/Pagination";
import { GetUserList, userDelete, userSave,getRoleList,setStatus,resetPwd } from "../../api/userMG";
export default {
  data() {
    return {
      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      title: "添加用户",
      isEditOrAdd:true, //是添加还是修改界面，控制是否禁用用户名表单
      editFormVisible: false, //控制编辑页面显示与隐藏
      // 编辑与添加
      editForm: {
        userId: "",
        userName: "",
        nickName: "",
        roleList:[],
        phonenumber: "",
        email: "",
        sex: "",
        userType:"1",
        token: localStorage.getItem("logintoken"),
    
      },

      // 选择数据
      selectdata: [],
      // rules表单验证
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        nickName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        // roleId: [{ required: true, message: "请选择角色", trigger: "blur" }],
        roleList: [{ required: true, message: "请选择角色", trigger: "blur" }],
        userType: [{ required: true, message: "请选择性", trigger: "blur" }],
        phonenumber: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1(3\d|47|5((?!4)\d)|7(0|1|[6-8])|8\d)\d{8,8}$/,
            required: true,
            message: "请输入正确的手机号",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            pattern:
              /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            required: true,
            message: "请输入正确的邮箱",
            trigger: "blur",
          },
        ],
        sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
      },
      // 请求数据参数
      formInline: {
        pageNum: 1,
        pageSize: 10,
        userName: "",
        phonenumber: "",
        status: "",
        userType: "",
      },
      //用户数据
      userData: [
        {
          roles:[{
          name:'11'
          }]
        }
        ],
      // 选中
      checkmenu: [],
      //参数role
      saveroleId: "",
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10,
      },

      //角色列表
      allRoles:[],
    };
  },
  // 注册组件
  components: {
    Pagination,
  },

  /**
   * 数据发生改变
   */
  watch: {},

  /**
   * 创建完毕
   */
  created() {
    //加载用户列表
    this.getdata(this.formInline);
    //加载角色列表
    this.getRoleData();
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    //获取角色列表
    getRoleData(){
      getRoleList().then((res)=>{
 this.loading = true;
       //获取角色列表
      getRoleList().then((res) => {
        this.loading = false;
        if (res.code != 200) {
          this.$message({
            type: "info",
            message: res.msg,
          });
        } else {
          console.log(res);
          this.allRoles = res.data;
        }
      });
      })
    },
    // 获取用户数据方法
    getdata(parameter) {
      this.loading = true;
      /***
       * 调用接口，注释上面模拟数据 取消下面注释
       */
      // 获取用户列表
      GetUserList(parameter).then((res) => {
        this.loading = false;
        if (res.code != 200) {
          this.$message({
            type: "info",
            message: res.msg,
          });
        } else {
          console.log(res.data);
          this.userData = res.data.items;
          // 分页赋值
          this.pageparm.currentPage = this.formInline.pageNum;
          this.pageparm.pageSize = this.formInline.pageSize;
          this.pageparm.total = res.data.totalNum;

        }
      });
    },
    // 分页插件事件
    callFather(parm) {
       this.formInline.pageNum = parm.currentPage;
      this.formInline.pageSize = parm.pageSize;
      this.getdata(this.formInline);
    },
    //搜索事件
    search() {
      this.formInline.pageNum=1
      this.getdata(this.formInline);
    },
    // 修改type
    editType: function (index, row) {
      this.loading = true;
      let parm = {
        lock: "",
        userId: "",
        token: localStorage.getItem("logintoken"),
      };
      parm.userId = row.userId;
      let lock = row.status;
      if (lock == 1) {
        parm.lock = 0;
      } else {
        parm.lock = 1;
      }
      // 修改状态
      setStatus(row.id).then((res) => {
        this.loading = false;
        if (res.code != 200) {
          this.$message({
            type: "info",
            message: res.msg,
          });
        } else {
          this.$message({
            type: "success",
            message: "状态修改成功",
          });
          this.getdata(this.formInline);
        }
      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.editFormVisible = true;
      if (row != undefined && row != "undefined") {
        //修改时将角色信息改到多选框中
        var roleList=[]
        for(var i =0;i<row.roles.length;i++){
          roleList.push(row.roles[i].id)
        };
        this.editForm.roleList=roleList;

        this.isEditOrAdd=true;
        this.title = "修改用户";
        this.editForm.userId = row.id;
        this.editForm.userName = row.userName;
        this.editForm.nickName = row.nickName;
        // this.editForm.roleId = row.roleId + "";
        // this.editForm.roleList = [3];
        this.editForm.phonenumber = row.phonenumber;
        this.editForm.email = row.email;
        this.editForm.sex = row.sex + "";
        
      } else {
        this.isEditOrAdd=false;
        this.title = "添加用户";
        this.editForm.userId = "";
        this.editForm.userName = "";
        this.editForm.nickName = "";
        // this.editForm.roleId = "";
        this.editForm.phonenumber = "";
        this.editForm.email = "";
        this.editForm.sex = "";
      }
    },
    // 编辑、添加提交方法
    submitForm(editData) {
      // this.editForm.roleList=JSON.stringify(this.editForm.roleList)
      console.log(editData)
      this.$refs[editData].validate((valid) => {
        if (valid) {
          // 请求方法
          userSave(this.editForm)
            .then((res) => {
              this.editFormVisible = false;
              this.loading = false;
              if (res.code == 200) {
                this.getdata(this.formInline);
                this.$message({
                  type: "success",
                  message: "数据保存成功！",
                });
              } else {
                this.$message({
                  type: "info",
                  message: res.msg,
                });
              }
            })
            .catch((err) => {
              this.editFormVisible = false;
              this.loading = false;
              this.$message.error("保存失败，请稍后再试！");
            });
        } else {
          return false;
        }
      });
    },


    // 关闭编辑、增加弹出框
    closeDialog(dialog) {
      if (dialog == "edit") {
        this.editFormVisible = false;
      }
    },
    // 删除用户
    deleteUser(index, row) {
      this.$confirm("确定要删除吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log("index" + index);
          console.log(row.id);
          // 删除
          userDelete(row.id)
            .then((res) => {
              if (res.code == 200) {
                this.$message({
                  type: "success",
                  message: "数据已删除!",
                });
                this.getdata(this.formInline);
              } else {
                this.$message({
                  type: "info",
                  message: res.msg,
                });
              }
            })
            .catch((err) => {
              this.loading = false;
              this.$message.error("数据删除失败，请稍后再试！");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除！",
          });
        });
    },
    // 重置密码
    resetpwd(index, row) {
      var userId=row.id;
      this.$confirm("确定要重置密码吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          resetPwd(userId)
            .then((res) => {
              if (res.code==200) {
                this.$message({
                  type: "success",
                  message: "重置密码成功！",
                });
                this.getdata(this.formInline);
              } else {
                this.$message({
                  type: "info",
                  message: res.msg,
                });
              }
            })
            .catch((err) => {
              this.loading = false;
              this.$message.error("重置密码失败，请稍后再试！");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消重置密码！",
          });
        });
    },
  },
};
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>

 